package com.nuoniu.sibanyun.service.cm.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.cm.CmContractClause;
import com.nuoniu.sibanyun.mapper.cm.CmContractClauseMapper;
import com.nuoniu.sibanyun.service.cm.ICmContractClauseService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 合同条款 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2021-10-21
 */
@Service
public class CmContractClauseServiceImpl extends ServiceImpl<CmContractClauseMapper, CmContractClause> implements ICmContractClauseService {

    @Override
    public List<CmContractClause> getList(CmContractClause contractClause) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<CmContractClause> queryWrapper = new QueryWrapper();
        queryWrapper.eq("company_id", userInfo.getCompanyId());

        if(StringUtils.isNotBlank(contractClause.getSearchKey())) {
            queryWrapper.and(wrapper -> wrapper.likeRight("code", contractClause.getSearchKey()).or().like("name", contractClause.getSearchKey()));
        }

        if(contractClause.getContractId() != null) {
            queryWrapper.eq("contract_id", contractClause.getContractId());
        }else {
            queryWrapper.isNull("contract_id");
        }

        return list(queryWrapper);
    }

    @Override
    public void saveClause(CmContractClause contractClause) {
        UserInfo userInfo = UserThreadLocal.get();
        contractClause.setCompanyId(userInfo.getCompanyId());
        CmContractClause clauseByName = baseMapper.getByName(contractClause);
        if(clauseByName != null && (clauseByName.getId() == null || !clauseByName.getId().equals(contractClause.getId()))) {
            throw new NuoNiuException("名称已存在");
        }

        CmContractClause clauseByCode = baseMapper.getByCode(contractClause);
        if(clauseByCode != null && (clauseByCode.getId() == null || !clauseByCode.getId().equals(contractClause.getId()))) {
            throw new NuoNiuException("编码已存在");
        }
        saveOrUpdate(contractClause);
    }
}
